package com.shujia.day16.udp.send.file2;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Server {
    public static void main(String[] args) throws IOException {
        String path = "";
        DatagramSocket dataNameSocket = new DatagramSocket(6666);
        DatagramSocket dataSocket  = new DatagramSocket(8888);

        try {
            System.out.println("Socket启动了...");
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            int readLen = 0;
            dataNameSocket.receive(datagramPacket);
            System.out.println("接收到数据了...");
            while ((readLen = datagramPacket.getLength()) > 0) {
                System.out.println("获取到一部分数据");
                path += new String(datagramPacket.getData(), 0, readLen);
                if (readLen != 1024) {
                    break;
                }
                dataNameSocket.receive(datagramPacket);
            }
        } catch (Exception e) {
            System.out.println("信息读取错误...");
        } finally {
            dataNameSocket.close();
        }


        int readLen = 0;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            System.out.println("开始创建输出流" + path);
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(path));

            byte[] imageBytes = new byte[1024];
            DatagramPacket imagePacket = new DatagramPacket(imageBytes, imageBytes.length);

            dataSocket.receive(imagePacket);
            while ((readLen = imagePacket.getLength()) > 0) {
                // TODO 将读取到的数据以IO流的方式保存下来
                System.out.println("获取到一部分Image数据");
                bufferedOutputStream.write(imagePacket.getData(), 0, readLen);
                bufferedOutputStream.flush();
                if (readLen != 1024) {
                    break;
                }
                dataSocket.receive(imagePacket);
            }
        } catch (Exception e) {
            System.out.println("错误");
        } finally {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            dataSocket.close();
        }


    }
}
